package com.tpshion.chat.websocket;

import com.tpshion.chat.exception.MyException;
import com.tpshion.chat.exception.RespStatus;
import com.tpshion.chat.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import org.springframework.util.StringUtils;

/**
 * @Description: netty websocket 连接权限验证
 * @Author: tpshion
 * @Date: 2020/5/18 18:41
 * @Version: 1.0
 */
public class LoginHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) throws Exception {
        String uri = fullHttpRequest.uri();
        if(StringUtils.startsWithIgnoreCase(uri, "/wschat/") && uri.length() > 9){
            String token = uri.substring(uri.lastIndexOf("/") + 1);
            try {
                Claims claims = JwtUtil.checkToken(token);
                WebSocketServer.clients.put(claims.getId(), ctx.channel());
                WebSocketServer.unReadMsgList.forEach(item ->{
                    if(item.getUserId().equals(claims.getId())){
                        WebSocketServer.userMsg.put(ctx.channel(),item.getMsgList());
                        WebSocketServer.unReadMsgList.remove(item);
                    }
                });
                ctx.fireChannelRead(fullHttpRequest.setUri("/wschat").retain());
            }catch (Exception e){
                ctx.close();
                throw new MyException(RespStatus.TOKEN_ERROR);
            }
        }else{
            ctx.close();
        }
    }
}
